<?php defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! class_exists('Controller'))
{
	class Controller extends CI_Controller {}
}

class Auth extends Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->library('ion_auth');
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->database();
		$this->load->helper('url');
	}

	//redirect if needed, otherwise display the user list
	function index()
	{
		if (!$this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect('auth/login', 'refresh');
		}
		elseif (!$this->ion_auth->is_admin())
		{
			//redirect them to the home page because they must be an administrator to view this
			redirect($this->config->item('base_url'), 'refresh');
		}
		else
		{
			//set the flash data error message if there is one
			$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

			//list the users
			$this->data['users'] = $this->ion_auth->get_users_array();
			$this->load->view('auth/index', $this->data);
		}
	}

	//log the user in
	function login()
	{

		//		if ($this->ion_auth->logged_in())
		//		{
		//			redirect($this->config->item('base_url'), 'refresh');
		//			return;
		//		}

		//validate form input
		$this->form_validation->set_rules('email', 'email', 'required|valid_email');
		$this->form_validation->set_rules('password', 'password', 'required');

		if ($this->form_validation->run() == true)
		{ //check to see if the user is logging in
			//check for "remember me"
			$remember = (bool) $this->input->post('remember');

			if ($this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember))
			{ //if the login is successful
				//redirect them back to the home page

				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect($this->config->item('base_url'), 'refresh');
				return;
			}
			else
			{
				//if the login was un-successful
				//redirect them back to the login page
				//$this->session->set_flashdata('message', $this->ion_auth->errors());
				//redirect('auth/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
				$login_error = $this->ion_auth->error_for_key('login_error');
				if('LOGIN_ERROR_COMMON' == $login_error)
				$this->data['message'] = "The username or password you entered is incorrect.";
				else if('LOGIN_ERROR_NOTACTIVE' == $login_error)
				{
					if($this->ion_auth->logged_in())
					{
						$data['logged_in_username'] = "guest";
						$user = $this->ion_auth->get_user();

						if(strlen($user->username))
						{
							$data['logged_in_username'] = $user->username;
						}
						else if(strlen($user->email))
						{
							$temp = stristr($user->email,"@");
							if(strlen($temp))
							{
								$temp = str_replace($temp,'',$user->email);
								if(strlen($temp))
								$data['logged_in_username'] = $temp;
							}

						}

					}

					$this->data['js_file_path'] = '/application/js/activatepage.js';
					$this->data['css_file_path'] = '/application/css/activatepage.css';
					$this->data['title'] = '很抱歉, 您需要完成注册后才能登录使用!';
					$email_address = $this->form_validation->set_value('email');
					if(strlen($email_address))
					$this->data['email_address'] = $email_address;
					$this->load->view('header',$this->data);
					$this->load->view('auth/activatepage', $this->data);
					$this->load->view('footer');


					return ;
				}
			}

		}
		else
		{  //the user is not logging in so display the login page

			$errors_count = count($this->form_validation->_error_array);
			if ($errors_count > 0)
			$this->data['message'] = "The username or password you entered is incorrect.";
			else
			$this->data['message'] = "";
		}

		$this->data['css_file_path'] = '/application/css/loginpage.css';
		$this->data['title'] = 'Sign In';
		$this->data['header_title'] = 'Sign In';

		$this->load->view('header',$this->data);

		//set the flash data error message if there is one
		//$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

		$this->data['email'] = array('name' => 'email',
			'id' => 'email',
			'type' => 'text',
			'value' => $this->form_validation->set_value('email'),
		);
		$this->data['password'] = array('name' => 'password',
			'id' => 'password',
			'type' => 'password',
		);

		$this->load->view('auth/login', $this->data);
			
		$this->load->view('footer');

	}

	//log the user out
	function logout()
	{
		//log the user out
		$logout = $this->ion_auth->logout();

		//redirect them back to the page they came from
		redirect($this->config->item('base_url'), 'refresh');
	}

	//change password
	function change_password()
	{
		$this->form_validation->set_rules('old', 'Old password', 'required');
		$this->form_validation->set_rules('new', 'New Password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
		$this->form_validation->set_rules('new_confirm', 'Confirm New Password', 'required');

		if (!$this->ion_auth->logged_in())
		{
			redirect('auth/login', 'refresh');
		}
		$user = $this->ion_auth->get_user($this->session->userdata('user_id'));

		if ($this->form_validation->run() == false)
		{ //display the form
			//set the flash data error message if there is one
			$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

			$this->data['old_password'] = array('name' => 'old',
				'id' => 'old',
				'type' => 'password',
			);
			$this->data['new_password'] = array('name' => 'new',
				'id' => 'new',
				'type' => 'password',
			);
			$this->data['new_password_confirm'] = array('name' => 'new_confirm',
				'id' => 'new_confirm',
				'type' => 'password',
			);
			$this->data['user_id'] = array('name' => 'user_id',
				'id' => 'user_id',
				'type' => 'hidden',
				'value' => $user->id,
			);

			//render
			$this->load->view('auth/change_password', $this->data);
		}
		else
		{
			$identity = $this->session->userdata($this->config->item('identity', 'ion_auth'));

			$change = $this->ion_auth->change_password($identity, $this->input->post('old'), $this->input->post('new'));

			if ($change)
			{ //if the password was successfully changed
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				$this->logout();
			}
			else
			{
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect('auth/change_password', 'refresh');
			}
		}
	}

	//forgot password
	function forgot_password()
	{
		//get the identity type from config and send it when you load the view
		$identity = $this->config->item('identity', 'ion_auth');
		$this->form_validation->set_rules('email', 'email', 'required|valid_email');
		
		if ($this->form_validation->run() == false)
		{
			if(validation_errors())
				$this->data['email_error'] = '请输入有效的邮箱地址';
		}
		else
		{
			$forgotten = $this->ion_auth->forgotten_password($this->input->post($identity));
			
			if ($forgotten)
				$this->data['alert_message'] = '邮件已发送到您指定的邮箱，请注意查收！';
			else
				$this->data['alert_message'] = '很抱歉，邮件发送失败，请检查您的网络！';

		}
		
		$this->data['css_file_path'] = '/application/css/forgot_password.css';
		$this->data['identity'] = $identity;
		$this->load->view('header',$this->data);
		$this->load->view('auth/forgot_password', $this->data);
		$this->load->view('footer');
	}

	//reset password - final step for forgotten password
	public function reset_password($code)
	{
		$reset = $this->ion_auth->forgotten_password_complete($code);

		if ($reset)
		{  //if the reset worked then send them to the login page
			$this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect("auth/login", 'refresh');
		}
		else
		{ //if the reset didnt work then send them back to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect("auth/forgot_password", 'refresh');
		}
	}

	//activate the user
	function activate($id, $code=false)
	{
		if ($code !== false)
		$activation = $this->ion_auth->activate($id, $code);
		else if ($this->ion_auth->is_admin())
		$activation = $this->ion_auth->activate($id);


		if ($activation)
		{
			//redirect them to the auth page
			//$this->session->set_flashdata('message', $this->ion_auth->messages());
			//redirect("auth", 'refresh');
			redirect("auth/login",'refresh');
		}
		else
		{
			//redirect them to the forgot password page
			//				$this->session->set_flashdata('message', $this->ion_auth->errors());
			//				redirect("auth/forgot_password", 'refresh');

			echo "activate_unsuccessful";
		}
	}

	//deactivate the user
	function deactivate($id = NULL)
	{
		// no funny business, force to integer
		$id = (int) $id;

		$this->load->library('form_validation');
		$this->form_validation->set_rules('confirm', 'confirmation', 'required');
		$this->form_validation->set_rules('id', 'user ID', 'required|is_natural');

		if ($this->form_validation->run() == FALSE)
		{
			// insert csrf check
			$this->data['csrf'] = $this->_get_csrf_nonce();
			$this->data['user'] = $this->ion_auth->get_user_array($id);
			$this->load->view('auth/deactivate_user', $this->data);
		}
		else
		{
			// do we really want to deactivate?
			if ($this->input->post('confirm') == 'yes')
			{
				// do we have a valid request?
				if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
				{
					show_404();
				}

				// do we have the right userlevel?
				if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
				{
					$this->ion_auth->deactivate($id);
				}
			}

			//redirect them back to the auth page
			redirect('auth', 'refresh');
		}
	}

	//create a new user
	function create_user()
	{
		//		$this->data['title'] = "Create User";

		//		if ($this->ion_auth->logged_in())
		//		{
		//			echo "logged in";
		//			//redirect('auth', 'refresh');
		//		}

		//		if($this->ion_auth->is_admin())
		//		{
		//			echo "is_admin";
			//			//redirect('auth', 'refresh');
			//		}

			//validate form input
			//$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
			//$this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
			$this->form_validation->set_rules('email', 'email', 'required|valid_email');
			//$this->form_validation->set_rules('phone1', 'First Part of Phone', 'required|xss_clean|min_length[3]|max_length[3]');
			//$this->form_validation->set_rules('phone2', 'Second Part of Phone', 'required|xss_clean|min_length[3]|max_length[3]');
			//$this->form_validation->set_rules('phone3', 'Third Part of Phone', 'required|xss_clean|min_length[4]|max_length[4]');
			//$this->form_validation->set_rules('company', 'Company Name', 'required|xss_clean');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
			$this->form_validation->set_rules('password_confirm', 'password_confirm', 'required');

			if ($this->form_validation->run() == true)
			{
				//$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
				$email = $this->input->post('email');
				$password = $this->input->post('password');

				if($this->_check_captcha())
				{
					if($this->ion_auth->register($email, $password))
					{
						if($this->ion_auth->logged_in())
						{
							$data['logged_in_username'] = "guest";
							$user = $this->ion_auth->get_user();

							if(strlen($user->username))
							{
								$data['logged_in_username'] = $user->username;
							}
							else if(strlen($user->email))
							{
								$temp = stristr($user->email,"@");
								if(strlen($temp))
								{
									$temp = str_replace($temp,'',$user->email);
									if(strlen($temp))
									$data['logged_in_username'] = $temp;
								}

							}

						}

						$this->data['js_file_path'] = '/application/js/activatepage.js';
						$this->data['css_file_path'] = '/application/css/activatepage.css';
						$this->data['title'] = '马上激活邮件, 完成注册吧!';
						$email_address = $this->form_validation->set_value('email');
						if(strlen($email_address))
						$this->data['email_address'] = $email_address;
						$this->load->view('header',$this->data);
						$this->load->view('auth/activatepage', $this->data);
						$this->load->view('footer');

						return;
					}
				}
				else
				{
					$this->data['captcha_error'] = "验证码输入错误";
				}
					
			}


			//check email
			$email_error = '';
			$temp = $this->form_validation->error('email');
			if(strlen($temp))
			{
				$email_error = '请输入有效的邮箱地址';
			}
			else
			{
				$signup_error = $this->ion_auth->error_for_key('signup_error');
				if('SIGNUP_ERROR_EMAILEXISTING' == $signup_error)
				$email_error = "此邮箱已被注册，请另换一个";
			}

			if(strlen($email_error))
			$this->data['email_error'] = $email_error;

			//check password
			$password_error = '';
			$temp = $this->form_validation->error('password');
			if(strlen($temp))
			{
				if(strpos($temp,"_matches",0))
				$password_error = '两次输入的密码不一致';
				else
				$password_error = '请输入6－20位英文字母或数字组成的密码';

				$this->data['password_error'] = $password_error;
			}

			//make captcha
			$this->load->helper('captcha');

			$vals = array(
	    'img_path' => './captcha/',
	    'img_url' => $this->config->item('base_url').'captcha/',
				'font_path'=>'./system/fonts/arial.ttf'
				);

				$cap = create_captcha($vals);
				$this->data['captcha'] = $cap;

				$captcha_data = array(
			    'time' => $cap['time'],
			    'ip' => $this->input->ip_address(),
			    'word' => $cap['word']
				);

				$query = $this->db->insert_string('captcha', $captcha_data);
				$this->db->query($query);

				//load view
				$this->data['css_file_path'] = '/application/css/signuppage.css';
				$this->data['title'] = 'Sign Up';

				$this->data['email'] = array('name' => 'email',
			'id' => 'email',
			'type' => 'text',
			'value' => $this->form_validation->set_value('email'),
				);

				$this->data['password'] = array('name' => 'password',
			'id' => 'password',
			'type' => 'password',
			'value' => $this->form_validation->set_value('password'),
				);
				$this->data['password_confirm'] = array('name' => 'password_confirm',
			'id' => 'password_confirm',
			'type' => 'password',
			'value' => $this->form_validation->set_value('password_confirm'),
				);

				$this->load->view('header',$this->data);
				$this->load->view('auth/create_user', $this->data);
				$this->load->view('footer');
		}
		
		function settings()
		{
			
			if($this->ion_auth->logged_in())
			{
				$data['logged_in_username'] = "guest";
				$user = $this->ion_auth->get_user();

				if(strlen($user->username))
				{
					$data['logged_in_username'] = $user->username;
				}
				else if(strlen($user->email))
				{
					$temp = stristr($user->email,"@");
					if(strlen($temp))
					{
						$temp = str_replace($temp,'',$user->email);
						if(strlen($temp))
						$data['logged_in_username'] = $temp;
					}

				}

			}

			$this->data['js_file_path'] = '/application/js/settings.js';
			$this->data['css_file_path'] = '/application/css/settings.css';
			$this->load->view('header',$this->data);
			$this->load->view('auth/settings', $this->data);
			$this->load->view('footer');
		}

		function _get_csrf_nonce()
		{
			$this->load->helper('string');
			$key = random_string('alnum', 8);
			$value = random_string('alnum', 20);
			$this->session->set_flashdata('csrfkey', $key);
			$this->session->set_flashdata('csrfvalue', $value);

			return array($key => $value);
		}

		function _valid_csrf_nonce()
		{
			if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
			$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
			{
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		}
			
		function _check_captcha()
		{
			//$firephp = FirePHP::getInstance(true);
			$expiration = time() - 3600; // 1小时超时

			// 首先删除验证码文件
			$query = $this->db->query("SELECT time FROM captcha WHERE time < ".$expiration);
			foreach ($query->result_array() as $row)
			{
				$time = $row['time'];

				if(strlen($time))
				{
					$captcha_image_path = "./captcha/".$time.".jpg";

					//$firephp->log($captcha_image_path);

					if(file_exists($captcha_image_path)){
						unlink($captcha_image_path);
					}
				}
					
			}

			//从数据库种删除旧的验证码
			$this->db->query("DELETE FROM captcha WHERE time < ".$expiration);

			// 然后再看是否有验证码存在:
			$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip = ? AND time > ?";
			$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
			$query = $this->db->query($sql, $binds);
			$row = $query->row();

			if ($row->count == 0)
			{
				return FALSE;
			}

			return TRUE;
		}
			
		function send_activate_email()
		{
			$email = $_GET['email'];
			if(strlen($email))
			{
				if($this->ion_auth->send_activate_email($email))
				{
					if($this->ion_auth->logged_in())
					{
						$data['logged_in_username'] = "guest";
						$user = $this->ion_auth->get_user();

						if(strlen($user->username))
						{
							$data['logged_in_username'] = $user->username;
						}
						else if(strlen($user->email))
						{
							$temp = stristr($user->email,"@");
							if(strlen($temp))
							{
								$temp = str_replace($temp,'',$user->email);
								if(strlen($temp))
								$data['logged_in_username'] = $temp;
							}

						}

					}

					$this->data['js_file_path'] = '/application/js/activatepage.js';
					$this->data['css_file_path'] = '/application/css/activatepage.css';
					$this->data['title'] = '确认邮件重发成功!';
					$this->data['email_address'] = $email;

					$this->load->view('header',$this->data);
					$this->load->view('auth/activatepage', $this->data);
					$this->load->view('footer');

					return;
				}
			}
		}

	}
